import React, { useState, useEffect } from 'react'
import "./TodoList.css"
//调用子组件
import TodoHeader from './TodoHeader/TodoHeader'
import TodoMain from './TodoMain/TodoMain'
import TodoFooter from './TodoFooter/TodoFooter'
import axios from './utils/http'
//导入nanoid
import { nanoid } from 'nanoid'

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

export default function TodoList() {
    //初始化状态数据
    //初始化数组地址假设0x100
    let [todolists, setTodolists] = useState([]);

    //调用useEffect钩子函数
    useEffect(() => {
        //单独声明一个async函数
        async function getAllTodolists() {
            //将ajax成功请求的结果值获取到并赋值给result变量接收
            /* try {
                let { data } = await axios.get('/todolistss');
                setTodolists(data);
            } catch (e) {
                //e为错误对象，里面包含了两个属性
                //一个是message（错误消息）
                //一个是stack（错误消息跟踪）
                console.log('发生错误了....');
                console.log(e);
                console.log(e.message);
                console.log(e.stack);
            } */

            let { data } = await axios.get('/todolists');
            setTodolists(data);
        }
        //调用
        getAllTodolists();
    }, [])

    //在父组件中声明一个可以让子组件来有权限来修改父组件中的状态数据
    let addnewTodo = async title => {
        //发送请求
        //post方法响应体是最新提交的数据
        let { data } = await axios.post('/todolists',
            {
                id: nanoid(),
                title,
                done: false
            });
        //修改状态数据
        //初始化数组地址假设0x200
        setTodolists([
            ...todolists,
            data
        ])
        toast.success('添加任务成功');
        // toast.error('添加任务失败');
    }

    let checkOnetodo = async (id, done) => {
        //发送请求
        await axios.patch(`/todolists/${id}`, { done })
        //由于状态数据中哪一条对象都有可能被修改值，那么我们可以遍历按照id条件做更改
        let newtodolists = todolists.map(item => {
            //判断
            if (item.id === id) {
                item.done = done;
            }
            return item;
        });
        setTodolists(newtodolists);
    }

    let deleteOneTodo = async id => {
        // console.log('删除了....');
        // console.log(id);
        //原生数组中删除的方法：pop() - 末尾项删除 、shift() - 开头项删除、splice() - 任意项删除

        // let arr = [1, 2, 3, 4];
        // console.log(arr.splice(1, 1)); //返回的是那个被删除的项

        //发送请求
        await axios.delete(`/todolists/${id}`);
        let newtodolists = todolists.filter(item => item.id !== id);
        setTodolists(newtodolists);
        toast.success('删除任务成功');
    }

    let checkAllTodo = done => {
        //批量修改每一条任务中的done属性值
        todolists.map(async item => {
            //发送请求，逐条更新
            await axios.patch(`/todolists/${item.id}`, { done });
        })
        // console.log(done);
        //批量更新状态数据的每一项里面的done的值
        let newtodolists = todolists.map(item => {
            item.done = done;
            return item;
        })
        setTodolists(newtodolists);
    }

    let clearAlltodos = () => {
        todolists.filter(item => item.done).map(async item => {
            //逐条按照id条件进行删除
            await axios.delete(`/todolists/${item.id}`);
        })
        let newtodolists = todolists.filter(item => item.done === false);
        setTodolists(newtodolists);
        toast.success('删除任务成功');
    }

    return (
        <div className="todo-container">
            <div className="todo-wrap">
                <ToastContainer />
                {/* 调用头部组件 */}
                <TodoHeader addnewTodo={addnewTodo}></TodoHeader>
                <TodoMain todolists={todolists} checkOnetodo={checkOnetodo} deleteOneTodo={deleteOneTodo} />
                <TodoFooter checkAllTodo={checkAllTodo} todolists={todolists} clearAlltodos={clearAlltodos}></TodoFooter>
            </div>
        </div>
    )
}
